<template>
  <div class="activity-editor">
    <table-title
        title="发布公告"
        button-mode="back"
        :back-path="'/admin/activity'"
        icon="el-icon-s-order">
    </table-title>

    <!-- form -->
    <div class="form-content">
      <el-form ref="form" :model="form" :rules="formRules" label-width="100px">
        <el-form-item label="标题图">
          <el-upload
              drag
              class="avatar-uploader"
              name="file"
              :action="this.$store.state.api + '/app/order/PictureUpload'"
              :show-file-list="false"
              :on-success="handleSuccess"
              :before-upload="beforeUpload">
            <el-avatar
                v-if="imgUrl"
                :src="imgUrl"
                :size="178"
                shape="square"
                class="avatar">
            </el-avatar>
            <i v-else class="el-icon-plus icon"></i>
          </el-upload>
        </el-form-item>

        <el-row>
          <el-col :span="14">
            <el-form-item label="活动名称" prop="activityName" key="activityName">
              <el-input v-model="form.activityName" placeholder="请输入活动名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="14">
            <el-form-item label="活动地址">
              <el-input v-model="form.address" prop="address" placeholder="请输入活动地址"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="14">
            <el-form-item label="活动时间">
              <el-date-picker
                  v-model="form.time"
                  type="datetime"
                  placeholder="请选择活动时间"
                  prop="time">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="14">
            <el-form-item label="状态">
              <el-select v-model="form.status" placeholder="请选择活动状态">
                <el-option label="未开始" value="0"></el-option>
                <el-option label="已结束" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="18">
            <el-form-item label="活动详情" class="editor-container">
              <quill-editor v-model="form.content" :options="editorOption"></quill-editor>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row class="action-button">
          <el-col :span="18" align="right">
            <el-button type="danger" icon="el-icon-close" @click="back">取消</el-button>
            <el-button type="primary" icon="el-icon-edit" @click="confirm">
              {{ editID == -1 ? '新增' : '保存' }}
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
//引用富文本编辑器
import VueQuillEditor from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import TableTitle from "../../../components/TableTitle";

import modelAct from "../../../models/activity";

Vue.use(VueQuillEditor);


export default {
  name: 'ActivityEditor',
  components: {TableTitle},
  created() {
    // 获取参数
    this.editID = this.$route.params.id || -1;
    // 默认状态
    this.form.status = '0';

    // 编辑信息，获取信息
    if (this.editID != -1) this.getData();
  },
  data() {
    return {
      // 正在编辑的
      editID: -1,

      // 数据
      form: {
        /*"activityId": 0,
        "activityName": "string",
        "address": "string",
        "content": "string",
        "status": "string",
        "thumb": "string",
        "time": "2021-04-24T07:26:20.419Z",
        "userId": 0*/
        "status": "0"
      },
      // 头像
      imgUrl: '',

      // 校验规则
      formRules: {
        activityName: [
          {required: true, message: '请输入标题', trigger: 'blur'},
          {min: 1, max: 100, message: '标题长度在1到100个字符', trigger: 'blur'}
        ]
      },

      // 富文本
      editorOption: {
        placeholder: '请输入活动详情',
      }
    };
  },
  methods: {
    /**
     * 获取信息
     */
    getData() {
      modelAct.getById(this.editID).then((data) => {
        // 无数据
        if (data == null) {
          this.$message({
            type: 'error',
            message: '加载数据失败！',
            onClose: () => {
              this.$router.replace('/admin/activity');
            }
          });
        }
        else {
          this.form = data;
          this.imgUrl = this.form.thumb;
        }
      });
    },

    /**
     * 返回
     */
    back() {
      this.$router.replace('/admin/activity');
    },

    /**
     * 保存
     */
    confirm() {
      // 新增
      if (this.editID == -1) {
        this.axios.post(this.$store.state.api + '/activity/add', {
          activityName: this.form.activityName || '',
          address: this.form.address || '',
          content: this.form.content || '',
          status: this.form.status || '',
          thumb: this.form.thumb || '',
          time: new Date().format("yyyy-MM-ddThh:mm:ss.SZ"),
          userId: this.$store.state.userData.userId
        }).then((response) => {
          this.$message({
            type: response.data.data ? 'success' : 'error',
            message: response.data.data ? '添加成功！' : '添加失败！',
            duration: 1000,
            onClose: () => {
              this.back();
            }
          });
        }).catch((error) => {
          console.log(error);
        });
      }
      // 更新
      else {
        this.axios.put(this.$store.state.api + '/activity/update', [{
          activityName: this.form.activityName || '',
          address: this.form.address || '',
          content: this.form.content || '',
          status: this.form.status || '',
          thumb: this.form.thumb || '',
          activityId: this.editID
        }]).then((response) => {
          this.$message({
            type: response.data.data ? 'success' : 'error',
            message: response.data.data ? '修改成功！' : '修改失败！',
            duration: 1000,
            onClose: () => {
              this.back();
            }
          });
        }).catch((error) => {
          console.log(error);
        });
      }
    },

    /**
     * 上传成功
     *
     * @param res
     */
    handleSuccess(res) {
      console.log(res);
      this.form.thumb = res.data;
      this.imgUrl = res.data;
    },

    /**
     * 检测图片大小
     *
     * @param file
     * @return {boolean}
     */
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 <= 3;
      if (!isLt2M) {
        this.$message.error("头像大小不能超过3MB!");
      }
      return isLt2M;
    },
  },
};
</script>

<style lang="less" scoped>
@import "../../../assets/less/base.less";

.activity-editor {
  color: @fontColor;
  min-height: 100%;
  background: white;
}
</style>

<style lang="less">
.activity-editor {
  // Editor
  .editor-container {
    height: 500px;

    .el-form-item__content {
      line-height: inherit;
      height: 100%;

      .quill-editor {
        height: 85%;
      }
    }
  }
}
</style>